package edu.ynu.se.xiecheng.achitectureclass.project.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

@Component
@Slf4j
public class OssUtils {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    private OSS ossClient;

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    public String uploadImage(String imageUrl) {
        try {
            // 下载萤石云图片
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();

            // 生成OSS存储路径
            String fileName = "captures/" + UUID.randomUUID().toString() + ".jpg";

            // 上传到OSS
            ossClient.putObject(bucketName, fileName, inputStream);

            // 生成可访问的URL
            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (Exception e) {
            log.error("Upload to OSS failed", e);
            throw new RuntimeException("Upload to OSS failed", e);
        }
    }
}